<template>
  <router-view></router-view>
  <div class="storeInfo-box" v-if="isIndex">
    <div class="content-box w-card">
      <div class="content-title">
        <h1>商户列表</h1>
        <el-button style="margin-left:auto;" type="primary" @click="addUser">开户</el-button>
        <el-button @click="deriveHandle">全部导出</el-button>
      </div>
      <div class="content-table">
        <div class="search-box">
          <div class="form-item">
            <span>商户名称：</span>
            <el-input v-model="searchForm.shopName" clearable placeholder="请输入商户名称" />
          </div>
          <div class="form-item">
            <span>合作方式：</span>
            <el-select style="width:100%" v-model="searchForm.cooperateType" clearable>
              <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </div>
          <div class="form-item">
            <span>商户状态：</span>
            <el-select style="width:100%" v-model="searchForm.operationalStatus" clearable>
              <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </div>
        </div>
        <div class="search-box" style="margin-top:20px">
          <div class="form-item">
            <span>推荐人：</span>
            <el-select style="width:100%" v-model="searchForm.tjUnique" clearable>
              <el-option v-for="item in tjOptions" :key="item.tjUnique" :label="item.tjName" :value="item.tjUnique" />
            </el-select>
          </div>
          <div class="form-item" style="width:30% !important;max-width:400px;">
            <span>开通时间：</span>
            <el-date-picker v-model="searchForm.date" type="datetimerange" range-separator="至" start-placeholder="开始时间"
              end-placeholder="结束时间" />
          </div>
          <el-button type="primary" @click="searchHandle">搜索</el-button>
        </div>
        <div class="table-box">
          <el-table :height="tableHeight" :header-cell-style="{background:'#d6dee5',color:'#000000',fontSize:'14px'}"
            :cell-style="{fontSize:'14px',color:'#7b7b7d'}" :data="tableData" stripe @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column type="index" width="55" label="序号" align="center" />
            <el-table-column prop="shopName" label="商户名称" align="center">
              <template v-slot="scope">
                <el-link type="primary" @click="lookDetail(scope.row)">{{ scope.row.shopName || '' }}</el-link>
              </template>
            </el-table-column>
            <el-table-column prop="auditStatus" label="商户类型" align="center">
              <template v-slot="scope">
                {{ scope.row.auditStatus == 1 ? '个人商户' : scope.row.auditStatus == 2 ? '企业商户' : '' }}
              </template>
            </el-table-column>
            <el-table-column prop="cooperateType" label="合作方式" align="center" width="130">
              <template v-slot="scope">
                {{ scope.row.cooperateType == 1 ? '代理(H5链接)' : scope.row.cooperateType == 2 ? '分销(API对接)' : scope.row.cooperateType == 3 ? '混合(代理+分销)' : '' }}
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="开通时间" align="center" width="170">
              <template v-slot="scope">
                {{ scope.row.createTime ? getDateTime(scope.row.createTime)[6] : '' }}
              </template>
            </el-table-column>
            <el-table-column prop="deadline" label="可用期限" align="center">
              <template v-slot="scope">
                {{ scope.row.deadline || '' }}
              </template>
            </el-table-column>
            <el-table-column prop="createUserName" label="联系方式" align="center" width="180">
              <template v-slot="scope">
                <span>{{ scope.row.shopUserName || '' }}</span>
                <span>({{ scope.row.shopUserPhone || '' }})</span>
              </template>
            </el-table-column>
            <el-table-column prop="tjName" label="推荐人" align="center">
              <template v-slot="scope">
                {{ scope.row.tjName || '' }}
              </template>
            </el-table-column>
            <el-table-column prop="operationalStatus" label="状态" align="center">
              <template v-slot="scope">
                <span :class="'state'+scope.row.operationalStatus"></span>
                {{ scope.row.operationalStatus == 0 ? '禁用' : '启用' }}
              </template>
            </el-table-column>
            <el-table-column prop="sysBalance" label="账户余额(元)" align="center">
              <template v-slot="scope">
                {{ numFormat(scope.row.sysBalance/10000) || '' }}
              </template>
            </el-table-column>
            <el-table-column prop="incomeBalance" label="佣金余额(元)" align="center">
              <template v-slot="scope">
                {{ numFormat(scope.row.incomeBalance/10000) || '' }}
              </template>
            </el-table-column>
            <el-table-column prop="operations" label="操作" align="center" width="160" fixed="right">
              <template v-slot="scope">
                <el-link v-if="scope.row.operationalStatus == 0" style="font-size:14px;" type="primary"
                  @click="handleClick(1,scope.row)">启用</el-link>
                <el-link v-if="scope.row.operationalStatus == 1" style="font-size:14px;" type="danger"
                  @click="handleClick(2,scope.row)">禁用</el-link>
                <el-link style="font-size:14px;margin-left:10px;" type="primary" @click="editHandle(scope.row)">编辑</el-link>
              </template>
            </el-table-column>
          </el-table>
          <div class="table-footer">
            <div>
              <el-button :disabled="chooseList.length == 0" type="warning" plain @click="handleClick(1)">批量启用</el-button>
              <el-button :disabled="chooseList.length == 0" plain @click="handleClick(2)">批量禁用</el-button>
              <el-button :disabled="chooseList.length == 0" plain @click="handleClick(3)">批量导出</el-button>
            </div>
            <el-pagination v-model:currentPage="page" v-model:page-size="size" :page-sizes="[10, 20, 50, 100]" small
              :background="true" layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
              @current-change="handleCurrentChange" />
          </div>
        </div>
      </div>
    </div>
  </div>
  <confirm-pass ref="confirmPassRef" @verification="verification" />
</template>

<script>
import { onMounted, reactive, ref, toRefs, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { BlobDownLoad, getWindowWidthAndHeight, warningDeal, getDateTime, numFormat } from '@/utils/utils'
import confirmPass from '@/components/confirmPass.vue'
import api from './api'
export default {
  components: {
    confirmPass,
  },
  setup() {
    const route = useRoute()
    const router = useRouter()

    const confirmPassRef = ref(null)

    const state = reactive({
      handleClickType: null,
      handleClickData: null,
      tableHeight: 0,
      isIndex: true,
      page: 1,
      size: 10,
      total: 0,
      tableData: [],
      searchForm: {},
      chooseList: [],
      tjOptions: [],
      typeOptions: [
        {
          value: 1,
          label: '代理',
        },
        {
          value: 2,
          label: '分销',
        },
        {
          value: 3,
          label: '混合',
        },
      ],
      statusOptions: [
        {
          value: 1,
          label: '启用',
        },
        {
          value: 0,
          label: '禁用',
        },
      ],
    })

    watch(() => route.matched, (newVal, oldVal) => {
      setIsIndex()
    })

    function setIsIndex() {
      if (route.matched[route.matched.length - 1].path == '/storeInfo') {
        state.isIndex = true
        getTableData()
      } else {
        state.isIndex = false
      }
    }

    function getTableData() {
      const obj = {
        page: state.page,
        size: state.size,
        ...state.searchForm,
        createTimeStart: (state.searchForm.date && state.searchForm.date.length > 0) ? state.searchForm.date[0].getTime() : null,
        createTimeEnd: (state.searchForm.date && state.searchForm.date.length > 0) ? state.searchForm.date[1].getTime() : null,
      }
      api.shopSearch(obj).then(res => {
        if (res.code == '200') {
          state.tableData = res.data.records
          state.total = res.data.total
        } else {
          warningDeal(res.msg)
        }
      }).catch(err => {
        console.log(err)
      })
    }

    function deriveHandle() {
      //导出
      api.exportAll({ responseType: "blob" }).then(res => {
        const _fileName = decodeURIComponent(res.headers['content-disposition'].split(';')[1].split('=')[1])
        BlobDownLoad(res, _fileName)
      }).catch(err => {
        console.log(err)
      })
    }

    function deriveItemHandle() {
      const obj = {
        exportInfoList: state.chooseList,
        responseType: "blob",
      }
      api.exportAppoint(obj).then(res => {
        const _fileName = decodeURIComponent(res.headers['content-disposition'].split(';')[1].split('=')[1])
        BlobDownLoad(res, _fileName)
      }).catch(err => {
        console.log(err)
      })
    }

    function searchHandle() {
      state.page = 1
      getTableData()
    }

    function addUser() {
      //开户
      router.push({ path: '/storeInfo/editor' })
    }

    function handleSelectionChange(e) {
      state.chooseList = e
    }


    function handleClick(i, data) {
      state.handleClickType = i
      state.handleClickData = data
      let title = ''
      let msg = ''
      switch (i) {
        case 1:
          //启用
          title = '启用提示'
          msg = '是否确定启用选中商户？'
          confirmPassRef.value.dialogShow(title, msg, false)
          break
        case 2:
          //禁用
          title = '禁用提示'
          msg = '是否确定禁用选中商户？'
          confirmPassRef.value.dialogShow(title, msg, false)
          break
        case 3:
          //导出
          deriveItemHandle()
          break
      }
    }

    function verification() {
      switch (state.handleClickType) {
        case 1:
          //启用
          changeShopState(1)
          break
        case 2:
          //禁用
          changeShopState(0)
          break
      }
    }

    function getShopIds(list) {
      const shopIds = []
      list && list.map(item => {
        item.shopId && shopIds.push(item.shopId)
      })
      return shopIds
    }

    function changeShopState(operationalStatus) {
      let obj = {}
      if (state.handleClickData) {
        obj = {
          operationalStatus,
          shopIds: [state.handleClickData.shopId],
        }
      } else {
        obj = {
          operationalStatus,
          shopIds: getShopIds(state.chooseList),
        }
      }
      api.shopStateBatchUpdate(obj).then(res => {
        if (res.code == '200') {
          state.handleClickType = null
          state.handleClickData = null
          getTableData()
        } else {
          warningDeal(res.msg)
        }
      }).catch(err => {
        console.log(err)
      })
    }

    function handleCurrentChange(e) {
      state.page = e
      getTableData()
    }

    function handleSizeChange(e) {
      state.size = e
      getTableData()
    }

    function lookDetail(data) {
      router.push({ path: '/storeInfo/details', query: { shopId: data.shopId } })
    }

    function editHandle(data) {
      router.push({ path: '/storeInfo/edit', query: { shopId: data.shopId } })
    }

    function getTjOptions() {
      const obj = {

      }
      api.tuijianuser(obj).then(res => {
        if (res.code == '200') {
          state.tjOptions = res.data?.list
        }
      }).catch(err => {
        console.log(err)
      })
    }

    onMounted(() => {
      let winHeight = getWindowWidthAndHeight()
      state.tableHeight = winHeight.windowHeight - 340
      setIsIndex()
      getTjOptions()
    })

    return {
      ...toRefs(state),
      deriveHandle,
      searchHandle,
      addUser,
      handleSelectionChange,
      handleClick,
      confirmPassRef,
      verification,
      handleCurrentChange,
      handleSizeChange,
      getDateTime,
      numFormat,
      lookDetail,
      editHandle,
    }
  }
}
</script>

<style lang="scss" scoped>
.storeInfo-box {
  width: 100%;
  height: 100%;
  display: flex;
  flex-flow: column;
  gap: 20px;
  .tips-box {
    background: url("@a/imgs/tips-background.png") no-repeat;
    background-size: 100% 100%;
    color: #ffffff;
    box-sizing: border-box;
    padding: 20px;
    border-radius: 5px;
    > div {
      display: flex;
      align-items: center;
      gap: 10px;
    }
    > span {
      display: block;
      margin-top: 10px;
      font-size: 14px;
    }
  }
  .content-box {
    flex-grow: 1;
    box-sizing: border-box;
    padding: 20px;
    .content-title {
      display: flex;
      align-items: center;
      > h1 {
        font-size: 16px;
      }
    }
    .content-table {
      margin-top: 20px;
      .search-box {
        display: flex;
        align-items: center;
        gap: 20px;
        .form-item {
          width: 25%;
          max-width: 300px;
          display: flex;
          align-items: center;
          gap: 5px;

          > span {
            font-size: 14px;
            flex-shrink: 0;
          }
        }
      }
      .table-box {
        margin-top: 20px;
        .table-footer {
          margin-top: 20px;
          display: flex;
          align-items: center;
          justify-content: space-between;
        }
      }
    }
  }
}
.state0 {
  display: inline-block;
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background-color: #ff3939;
}
.state1 {
  display: inline-block;
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background-color: #03b615;
}
</style>